<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2021/07/17
 * Time: 10:07
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\order;

use app\admin\controller\BaseController;
use app\common\model\Channel;
use app\common\model\Orders;
use app\common\model\OrdersPick;
use app\common\model\OrdersPickInfo;
use app\common\model\ProductStore;
use app\common\service\orders\OrderService;

class PickController extends BaseController
{
    /**
     * 拣货单列表
     * @date 2021/07/17
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $pick = OrdersPick::order("is_end, pick_id desc");
            $this->searchModel($pick, [
                'eq' => ['is_end', 'is_print', 'pick_sn'],
                'times' => ['print_time'],
            ]);
            $limit = $this->getPageSize();
            $pick = $pick->paginate($limit);
            $this->assign('list', $pick->getCollection());
            $this->assign('page', $pick->render());
            return $this->fetch('lists');
        }
        $this->assign('is_show_generate', $this->user->hasPermissions('/order/pick/generate'));
        $this->assign("is_end", ["否", "是"]);
        $this->assign("is_print", ["否", "是"]);
        return $this->fetch('index');
    }

    /**
     * 查看拣货单
     * @date 2021/07/17
     * @author longli
     */
    public function look()
    {
        $pickId = $this->request->get("pick_id");
        $pick = OrdersPick::with(['info.order'])->get($pickId);
        if(empty($pick)) $this->error("拣货单不存在");
        $this->assign('pick', $pick);
        return $this->fetch('look');
    }

    /**
     * 拣货单详情
     * @date 2021/07/17
     * @author longli
     */
    public function info()
    {
        $pickId = $this->request->request("pick_id", '', 'trim');
        $pickSn = $this->request->request("pick_sn", '', 'trim');
        $pick = !empty($pickId) ? OrdersPick::get($pickId) : OrdersPick::get(["pick_sn" => $pickSn]);
        if(empty($pick)) $this->error("拣货单不存在");
        if($pick->is_end == OrdersPick::IS_YES) $this->error("拣货单已完成");
        $this->assign("pick", $pick);
        return $this->fetch('info');
    }

    /**
     * 单个点击打印
     * @date 2021/07/20
     * @author longli
     */
    public function print_label()
    {
        $infoId = $this->request->get("info_id");
        $pickInfo = OrdersPickInfo::get($infoId);
        if(empty($pickInfo)) $this->error("订单不存在");
        /**
         * @var Orders $order
         */
        $order = $pickInfo->order;
        // 验证订单是否有渠道和面单
        if(empty($order->channel_id)) $this->error("订单【{$order->order_sn}】未选择发货渠道");
        if(empty($order->label_url)) $this->error("订单【{$order->order_sn}】未生成面单");
        $order->printLabel(); // 更新面单打印状态
        $pickInfo->printLabel(); // 更新拣货单状态

        $channel = Channel::get($order->channel_id);
        $this->success("打印成功", "", [
            "user_id" => $this->user->id,
            "size" => $channel->getPrintSize(),
            "label_url" => $order->label_url,
            "is_end" => $pickInfo->pick->isEnd(),
            "type" => "pick-success",
        ]);
    }

    /**
     * 匹配订单
     * @date 2021/07/17
     * @author longli
     */
    public function order()
    {
        $pickId = $this->request->post('pick_id');
        $scanSku = $this->request->post('scan_sku', '', 'trim');
        $skus = $this->request->post('skus');
        $qty = $this->request->post('qty');
        if(empty($pickId) || empty($skus) || empty($qty))
            $this->error("非法操作", '', ["type" => "abnormal-operation"]);
        $pick = OrdersPick::get($pickId);
        if(empty($pick)) $this->error("拣货单不存在", '', ["type" => "order-not-exist"]);
        if(array_sum($qty) > $pick->max_qty) $this->error("匹配失败", '', ["type" => "match-fail"]);
        // 查找商品
        $store = ProductStore::getStoreBySku($scanSku);
        if(empty($store)) $this->error("商品不存在", '', ["type" => "product-not-exist"]);
        // 获取订单
        $pickInfo = $pick->findPick(array_combine($skus, $qty));

        $html = view('info_sku', [
            'store' => $store,
            'scan_sku' => $scanSku
        ])->getContent();

        // 匹配不成功，渲染模板并返回
        if(empty($pickInfo))
        {
            $this->error("", "", [
                'html' => $html,
                'scan_sku' => $scanSku
            ]);
        }
        /**
         * @var Orders $order
         */
        $order = $pickInfo->order;
        if(empty($order)) $this->error("订单不存在", '', ['type' => "order-not-exist"]);
        // 验证订单是否有渠道和面单
        if(empty($order->channel_id)) $this->error("订单【{$order->order_sn}】未选择发货渠道");
        if(empty($order->label_url)) $this->error("订单【{$order->order_sn}】未生成面单");
        // 更新拣货单状态
        $pickInfo->printLabel();
        // 更新面单打印状态
        $order->printLabel();
        // 拣货单是否匹配完成
        $channel = Channel::get($order->channel_id);
        $this->success("匹配成功", "", [
            "order" => $order,
            "size" => $channel->getPrintSize(),
            "is_end" => $pick->isEnd(),
            "html" => $html,
            "scan_sku" => $scanSku,
            "type" => $pick->isEnd() ? "pick-success" : "match-success",
        ]);
    }

    /**
     * 打印拣货单
     * @date 2021/07/19
     * @author longli
     */
    public function print_pick()
    {
        $pickId = $this->request->get('pick_id', '', 'trim');
        $pick = OrdersPick::get($pickId);
        if(empty($pick)) $this->error("拣货单不存在");
        $pick->is_print = OrdersPick::IS_YES;
        $pick->save();
        $byte = base64_encode(file_get_contents(OrderService::getRootPath($pick->pick_path)));
        $this->success('打印成功', '', ['file' => $byte]);
    }

    /**
     * 下载拣货单
     * @date 2021/12/25
     * @author longli
     */
    public function download()
    {
        $pickId = $this->request->get('pick_id', '', 'trim');
        $pick = OrdersPick::get($pickId);
        if(empty($pick)) $this->error("拣货单不存在");
        \app\common\service\export\BaseExport::download(OrderService::getRootPath($pick->pick_path));
    }

    /**
     * 重置面单打印状态
     * @date 2021/07/21
     * @author longli
     */
    public function reset()
    {
        $ids = $this->request->get("ids");
        $pickId = $this->request->get("pick_id");
        if(empty($ids)) $this->error("非法请求");
        OrdersPickInfo::whereIn("info_id", $ids)->update(["print_user" => 0]);
        OrdersPick::where("pick_id", $pickId)->update(["is_end" => OrdersPick::IS_NO]);
        $this->success("重置成功");
    }

    /**
     * 生成拣货单
     * @date 2021/07/19
     * @author longli
     */
    public function generate()
    {
        set_time_limit(0);
        $out = \think\Console::call('order_pick', ["--warehouse_id={$this->warehouse->warehouse_id}"])->fetch();
        !empty($out) ? $this->success('生成成功') : $this->error($out === null ? "生成失败" : "暂无订单可生成");
    }
}